package com.xinjian.jianba.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 工具类
 */
public final class Utils {

	private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);

	private Utils() {
	}

	/**
	 * 字符串转日期.
	 */
	public static Date StringToDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(dateString);
		} catch (ParseException e) {
			LOGGER.info("StringToDate---------:" + e);
		}
		return null;
	}

	/*
	 * 以下用于UUID的生成，使用静态共享变量 / xizhenhua
	 */
	private static Random random = null;
	private static StringBuilder sb1 = null;
	private static StringBuilder sb2 = null;
	private static StringBuilder sb3 = null;

	static {
		/*
		 * 以下用于UUID的生成，对静态共享变量进行初始化 / xizhenhua
		 */
		random = new Random();
		sb1 = new StringBuilder();
		sb2 = new StringBuilder();
		sb3 = new StringBuilder();
	}

	/**
	 * 生成UUID 算法：修饰(MD5(纳秒+一百万随机数+一百万随机数))
	 * 78a566-582a-09e5-e6bd-aae8-6f7a-959473
	 * 
	 * 评测： 生成1百万个UUID， 消耗时间：1894微秒 生成1亿个UUID， 消耗时间：135315微秒
	 * 
	 * 期间无异常，溢出等相关异常 期间CPU，内存使用稳定，无大幅波动情况
	 * 
	 * @param
	 * @return
	 * @exception
	 * @since JDK 1.7
	 */
	public static String generateUUID() {
		sb1.delete(0, sb1.length());
		sb2.delete(0, sb2.length());
		sb3.delete(0, sb3.length());
		sb1.append(System.nanoTime());
		sb1.append(random.nextInt(1000000));
		sb1.append(random.nextInt(1000000));
		sb2.append(MD5Util.MD5(sb1.toString()));
		sb3.append(sb2.substring(0, 6));
		sb3.append("-");
		sb3.append(sb2.substring(6, 10));
		sb3.append("-");
		sb3.append(sb2.substring(10, 14));
		sb3.append("-");
		sb3.append(sb2.substring(14, 18));
		sb3.append("-");
		sb3.append(sb2.substring(18, 22));
		sb3.append("-");
		sb3.append(sb2.substring(22, 26));
		sb3.append("-");
		sb3.append(sb2.substring(26, 32));

		return sb3.toString();
	}
	public static String getUUID(){
        UUID uuid=UUID.randomUUID();
        String str = uuid.toString(); 
        String uuidStr=str.replace("-", "");
        return uuidStr;
      }
    public static String convertTimestampToString(Timestamp timestamp){
    	if(timestamp==null){
    		return "";
    	}
    	String str=timestamp.toString().substring(0, 19);
    	return str;
    }
}
